/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MalfReportActivity.java   
 * @Package com.jiyi.activity.new_maintenance   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-4 下午4:26:00   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.bean.maintenance.RepairTask.RepairTaskItem;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.RepairTaskListEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.DateChooseDialog;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: MalfReportActivity
 * @Description:TODO(故障报告)
 * @author: HYM
 * @date: 2017-9-4 下午4:26:00
 * 
 */
public class MalfReportActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.tvFirst)
	TextView tvFirst;
	@BindView(R.id.tvSecond)
	TextView tvSecond;
	@BindView(R.id.tvPoint)
	TextView tvPoint;
	@BindView(R.id.etNo)
	EditText etNo;
	@BindView(R.id.tvPosition)
	TextView tvPosition;
	@BindView(R.id.tvCheckStatus)
	TextView tvCheckStatus;
	@BindView(R.id.etRecord)
	EditText etRecord;
	@BindView(R.id.etProductName)
	EditText etProductName;
	@BindView(R.id.etBrand)
	EditText etBrand;
	@BindView(R.id.et_create)
	EditText et_create;
	@BindView(R.id.et_replace)
	EditText et_replace;
	@BindView(R.id.etModel)
	EditText etModel;
	@BindView(R.id.etPrice)
	EditText etPrice;
	@BindView(R.id.etRepairPrice)
	EditText etRepairPrice;
	@BindView(R.id.state_equip)
	Spinner state_equip;
	@BindView(R.id.state_payer)
	Spinner state_payer;
	@BindView(R.id.llProduct)
	LinearLayout llProduct;

	String id;
	RepairTaskItem repairTaskItem;

	// 设备状态，付款方适配器,
	ArrayAdapter<String> stateEquipAdapter, statePayerAdapter;
	// 设备id,付款方id,进度id
	String stateEquipId = "", statePayerId = "";
	// 进度条
	Dialog dialog;
	// 是否展开产品详情
	boolean isExtendProduct = false;
	int parentType,parentPosition,childPosition;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_malf_report);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		getIntentData();
		setViewStatus();
		seTop();
		setAdapter();
		getData();

	}
	
	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	/**
	 * @author: HYM
	 * @Title: getData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-9-19
	 */
	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_REPAIR_RECORD_DETAIL, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								repairTaskItem = new Gson().fromJson(data,
										RepairTaskItem.class);
								setInfo();
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});

	}

	private void setAdapter() {
		stateEquipAdapter = new ArrayAdapter<String>(this,
				R.layout.item_spinner, getResources().getStringArray(
						R.array.equip_state));
		state_equip.setAdapter(stateEquipAdapter);
		state_equip.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				stateEquipId = getStateEquipId(position);
				state_equip.setTag(R.id.tag_view_select_value, stateEquipId);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		statePayerAdapter = new ArrayAdapter<String>(this,
				R.layout.item_spinner, getResources().getStringArray(
						R.array.payer_state));
		state_payer.setAdapter(statePayerAdapter);
		state_payer.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				statePayerId = getStatePayerId(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

	}

	private void getIntentData() {
		id = getIntent().getStringExtra("id");
		parentType = getIntent().getIntExtra("parentType",0);
		parentPosition = getIntent().getIntExtra("parentPosition",0);
		childPosition = getIntent().getIntExtra("childPosition",0);
	}

	private void seTop() {
		tvTitle.setText("填写实测记录");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("取消");
	}

	void setInfo() {
		tvFirst.setText(repairTaskItem.getBad_name());
		tvSecond.setText(repairTaskItem.getEquipment_name());
		tvPoint.setText(repairTaskItem.getInspection_name());
		tvPosition.setText(repairTaskItem.getPlace());
		// tvCheckStatus.setText(repairTaskItem.getAuditor_status());
	}

	private void setViewStatus() {
		// 设置日期控件不能输出
		et_create.setKeyListener(null);

		// 设置必填项检测提示
		etRecord.setTag(R.id.tag_view_empty, "实测记录不能为空");
		etNo.setTag(R.id.tag_view_empty, "设备编号不能为空");
		et_create.setTag(R.id.tag_view_empty, "生产日期不能为空");
		et_replace.setTag(R.id.tag_view_empty, "保持日期不能为空");
		etProductName.setTag(R.id.tag_view_empty, "产品名称不能为空");
		etBrand.setTag(R.id.tag_view_empty, "产品品牌不能为空");
		etModel.setTag(R.id.tag_view_empty, "设备型号不能为空");
		etPrice.setTag(R.id.tag_view_empty, "单价不能为空");
		etRepairPrice.setTag(R.id.tag_view_empty, "维修金额不能为空");
		state_equip.setTag(R.id.tag_view_empty, "设备状态不能为空");
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getStateEquipId   
	 * @Description: TODO(获取设备状态)   
	 * @param: @param position
	 * @param: @return      
	 * @return: String       
	 * @throws   
	 */  
	public String getStateEquipId(int position)
	{
		return position == 0 ? "" : String.valueOf(position-1);
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getStatePayerId   
	 * @Description: TODO(获取付款方)   
	 * @param: @param position
	 * @param: @return      
	 * @return: String       
	 * @throws   
	 */  
	public String getStatePayerId(int position) {
		return String.valueOf(position);
	}
	
	@OnClick({ R.id.tvBack, R.id.tvSearch, R.id.tvPost,R.id.rlMoreProduct,R.id.et_create })
	public void onClick(View view) {
		DateChooseDialog.Builder builder;
		switch (view.getId()) {
		case R.id.tvBack:
		case R.id.tvSearch:
			finish();
			break;
		case R.id.tvPost:
			//提交
			if (CheckUtil.checkView(etRecord,etNo,etProductName,etBrand,et_create,et_replace,etModel,state_equip,etPrice,etRepairPrice)) {
				doPost();
			}
			break;
		case R.id.et_create:
			//生产日期
			builder = new DateChooseDialog.Builder(this,et_create.getText().toString());
			builder.setTitle("选择日期");  
			builder.setTextView(et_create);
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
				public void onClick(DialogInterface dialog, int which) {  
					dialog.dismiss();  						
				}
			});
			
			builder.setNegativeButton("取消",  
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {  
					dialog.dismiss();  
				}  
			});  
			builder.create().show();
			break;
		case R.id.rlMoreProduct:
			if (isExtendProduct) {
				llProduct.setVisibility(View.GONE);
				isExtendProduct = false;
			}
			else {
				llProduct.setVisibility(View.VISIBLE);
				isExtendProduct = true;
			}
			break;
		default:
			break;
		}
	}
	
	private void doPost() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("bdid", id);
		params.put("record", etRecord.getText().toString());
		params.put("amount", etRepairPrice.getText().toString());
		params.put("price", etPrice.getText().toString());
		params.put("pro_name", etProductName.getText().toString());
		params.put("product", etBrand.getText().toString());
		params.put("pro_type", etModel.getText().toString());
		params.put("pro_date", et_create.getText().toString());
		params.put("pro_safe_date", et_replace.getText().toString());
		params.put("bh_code", etNo.getText().toString());
		params.put("payer", statePayerId);
		params.put("equip_status", stateEquipId);
		
		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_REPAIR_RECORD_UPLOAD, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								JSONObject dataJson = new JSONObject(data);
								String bdid = dataJson.getString("id");
//								
								ToastUtil.getInstances().showMsg(info);
								RepairTaskItem temp = new RepairTaskItem();
								temp.setId(bdid);
								EventBus.getDefault().post(new RepairTaskListEvent(parentType,parentPosition,childPosition,temp,1));
								finish();
							}
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						finally
						{
							hideDialog(dialog);
						}
						
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}
}
